package vip.linfeng.securitydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * @auth linfeng
 * @create 2025/8/9 9:43
 * @Description
 */
@Configuration
//@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(
                authorize -> authorize
                        // 对所有请求开启授权保护
                        .anyRequest()
                        // 已认证的请求会被自动授权
                        .authenticated()
                )
                // 使用默认登录页
//                .formLogin(withDefaults())
                // 使用自定义登录页
                .formLogin(form -> {
                    form.loginPage("/login")
                    // 无需授权即可访问当前页面
                    .permitAll()
                    // 自定义接收表单的用户名参数，默认值为username
                    .usernameParameter("myUserName")
                    // 自定义接收表单的密码参数，默认值为password
                    .passwordParameter("myPassword")
                    // 修改登录错误URI，默认值为/login?error
                    .failureUrl("/login?errorFailure")
                    // 使用自定义登录成功响应结果
                    .successHandler(new MyAuthenticationSuccessHandler())
                    // 使用自定义登录失败响应结果
                    .failureHandler(new MyAuthenticationFailureHandler());
                })
                .httpBasic(withDefaults());
        // 关闭csrf攻击防御
//        http.csrf(csrf -> csrf.disable());
        return http.build();
    }

//    @Bean
    public UserDetailsService userDetailsService() {
        DBUserDetailsManager manager = new DBUserDetailsManager();
        return manager;
    }

//    @Bean
    public UserDetailsService userDetailsServiceMemory() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder().username("linfeng").password("linfeng12138").roles("USER").build());
        return manager;
    }
}
